package org.linlinjava.litemall.wx.service;


import org.linlinjava.litemall.db.core.RedisCache;
import org.linlinjava.litemall.db.util.SpringUtils;
import java.util.UUID;
import java.util.concurrent.TimeUnit;


public class UserTokenManagerRedis {






    public static RedisCache getRedisCache() {
        return SpringUtils.getBean(RedisCache.class);

    }

    public static String generateToken(Integer id) {
        return createToken(id);
    }

    public static Integer getUserId(String token) {

        Integer userId = verifyTokenAndGetUserId(token);
        if (userId == null || userId == 0) {
            return null;
        }
        return userId;
    }


    public static String createToken(Integer userId) {
        RedisCache redisCache = getRedisCache();
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        redisCache.setCacheObject(token, userId, 30, TimeUnit.DAYS);
        return token;
    }

    public static Integer verifyTokenAndGetUserId(String token) {
        RedisCache redisCache = getRedisCache();
        if (redisCache.hasKey(token)) {
            Integer userId = Integer.parseInt(redisCache.getCacheObject(token).toString());
            redisCache.setCacheObject(token, userId, 30, TimeUnit.DAYS);
            return userId;
        } else {
            return 0;
        }
    }

}
